<script lang="ts" setup>
import type { FileInfo } from '@/index.d';
import { deleteFileInfo, getFileInfoByKeyWord, useLoginUserStore } from '@/index';
import {
  genFileId,
  type ElUpload,
  type UploadFile,
  type UploadFiles,
  type UploadProps,
  type UploadRawFile,
  type UploadUserFile
} from 'element-plus';

const props = defineProps({
  keyWord: {
    type: String,
    required: true
  },
  editable: {
    type: Boolean,
    default: false
  }
});

const imageUrl = ref<string>();
const { loginUser } = useLoginUserStore();
const headers = { Authorization: loginUser.token };
const fileList = ref<UploadUserFile[]>([]);

const extraData: FileInfo = {
  keyWord: props.keyWord
};
const handleSuccess: UploadProps['onSuccess'] = (_response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};

const beforeUpload: UploadProps['beforeUpload'] = rawFile => {
  extraData.creatorId = loginUser.id;
  extraData.updaterId = loginUser.id;
  extraData.name = rawFile.name;
  extraData.size = rawFile.size;
  extraData.uid = rawFile.uid;
  extraData.type = rawFile.type;
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片必须jpg格式');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('图片大小不能超过10MB!');
    return false;
  }
  return true;
};

const initFileList = async () => {
  const res = await getFileInfoByKeyWord(props.keyWord);
  if (res) {
    const uploadUserFile: UploadUserFile = {
      name: res?.name as string,
      uid: res.uid as number,
      url: res?.url,
      size: res.size,
      status: 'success',
      response: res
    };
    imageUrl.value = res.url!;
    fileList.value.length = 0;
    fileList.value.push(uploadUserFile);
  }
};

onMounted(async () => initFileList());

const uploadComponent = useTemplateRef<InstanceType<typeof ElUpload>>('uploadComponent');

const handleRemove = async (uploadFile: UploadFile, _uploadFiles: UploadFiles) => {
  deleteFileInfo('physicalDeleteByUid', uploadFile.uid);
  imageUrl.value = undefined;
};
//新上传的文件，之前文件列表里面的文件
const handleExceed = (files: UploadUserFile[], _fileList: UploadUserFile[]) => {
  // 清空之前文件列表里面的文件
  uploadComponent.value?.clearFiles();
  // 获取新上传的文件
  const file = files[0] as UploadRawFile;
  // 生成uid
  file.uid = genFileId();
  // 将新上传的文件添加到上传组件的清单中
  uploadComponent.value?.handleStart(file);
  uploadComponent.value!.submit();
};
const handleRemoveFile = () => {
  fileList.value.forEach(item => uploadComponent.value?.handleRemove(item as UploadFile));
};
</script>
<template>
  <el-upload
    v-model:file-list="fileList"
    ref="uploadComponent"
    class="avatar-uploader"
    action="/api/base/file/fileInfo/uploadOne"
    :limit="1"
    :data="extraData"
    :headers="headers"
    :show-file-list="false"
    :on-success="handleSuccess"
    :before-upload="beforeUpload"
    :auto-upload="true"
    multiple
    :drag="editable"
    @exceed="handleExceed"
    @remove="handleRemove"
  >
    <!-- <template #trigger>
      <el-button text type="success" v-if="editable">上传图片</el-button>
    </template> -->

    <el-icon class="el-icon--upload" v-if="editable"><upload-filled /></el-icon>
    <div class="el-upload__text" v-if="editable">把文件拖入此处或者<em>点击上传</em></div>

    <template #tip>
      <el-button text @click="handleRemoveFile" type="danger" v-if="editable && imageUrl">
        删除图片
      </el-button>
    </template>
  </el-upload>

  <div class="image-container">
    <el-image v-if="imageUrl" :src="imageUrl" class="image" fit="contain" />
  </div>
</template>
<style lang="scss" scoped>
.image-container {
  width: 100%;
  .image {
    height: 600px;
  }
}
</style>
